package enterprise

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"net/http"
	"strings"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetEnterprisePageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetEnterprisePageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetEnterprisePageApiLogic {
	hostname, _ := os.Hostname()
	return &GetEnterprisePageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetEnterprisePageApiLogic) GetEnterprisePageApi(req *types.GetEnterprisePageReq) (resp *types.EnterprisePageResp, err error) {
	// todo: add your logic here and delete this line
	offset, limit := utils.DbPage(req.PageNumber, req.PageSize)
	tx := dao.EnterpriseEntity.WithContext(l.ctx)
	if req.Name != "" {
		req.Name = strings.ReplaceAll(req.Name, "%", "\\%")
		req.Name = strings.ReplaceAll(req.Name, "_", "\\%")
		tx = tx.Where(dao.EnterpriseEntity.Name.Like("%" + req.Name + "%"))
	}
	if req.Person != "" {
		req.Person = strings.ReplaceAll(req.Person, "%", "\\%")
		req.Person = strings.ReplaceAll(req.Person, "_", "\\%")
		tx = tx.Where(dao.EnterpriseEntity.Person.Like("%" + req.Person + "%"))
	}
	if req.Status != "" {
		tx = tx.Where(dao.EnterpriseEntity.Status.Eq(cast.ToInt64(req.Status)))
	}
	if req.Mobile != "" {
		tx = tx.Where(dao.EnterpriseEntity.Mobile.Eq(req.Mobile))
	}
	enterpriseEntities, count, err := tx.Order(dao.EnterpriseEntity.ID.Desc()).FindByPage(offset, limit)
	if err != nil {
		return &types.EnterprisePageResp{
			Data: make([]types.EnterpriseResp, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      count,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	enterpriseIdList := k.Map(enterpriseEntities, func(item *model.EnterpriseEntity, index int) int64 {
		return item.ID
	})
	// 查询门店数量
	customerEntities, err := dao.EnterpriseCustomerEntity.WithContext(l.ctx).Where(dao.EnterpriseCustomerEntity.EnterpriseID.In(enterpriseIdList...)).Find()
	enterpriseCustomerMap := make(map[int64][]*model.EnterpriseCustomerEntity)
	if err == nil {
		enterpriseCustomerMap = k.GroupBy(customerEntities, func(item *model.EnterpriseCustomerEntity) int64 {
			return item.EnterpriseID
		})
	}
	enterpriseResps := k.Map(enterpriseEntities, func(item *model.EnterpriseEntity, index int) types.EnterpriseResp {
		entities := enterpriseCustomerMap[item.ID]
		return types.EnterpriseResp{
			EnterpriseModel: types.EnterpriseModel{
				ID:           item.ID,                                 // 主键id
				Name:         item.Name,                               // 企业名称
				Person:       item.Person,                             // 负责人
				Mobile:       item.Mobile,                             // 联系电话
				Logo:         item.Logo,                               // 企业logo
				Status:       item.Status,                             // 状态0：营业  1：停业
				ProvinceCode: item.ProvinceCode,                       // 省份id
				CityCode:     item.CityCode,                           // 城市id
				CountyCode:   item.CountyCode,                         // 县、区id
				TownCode:     item.TownCode,                           // 乡镇code
				Address:      item.Address,                            // 具体地址
				FullAddress:  item.FullAddress,                        // 拼接省市县地址
				CreatedAt:    utils.TimestampToString(item.CreatedAt), // 创建时间
				UpdatedAt:    utils.TimestampToString(item.UpdatedAt), // 更新时间
			},
			EnterpriseCustomerCount: int64(len(entities)), // 门店数量
		}
	})
	return &types.EnterprisePageResp{
		Data: enterpriseResps,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
